<?php

abstract class Admin_Model_MapperAbstract {
	/**
	 *
	 * @var Zend_Db_Table_Abstract
	 */
	protected $_dbTable;

		
	public function __construct($db) {
		
	}
	
	/**
	 * 
	 * @return Zend_Db_Table_Abstract
	 */
	public function getDbTable() {
		return $this->_dbTable;
	}
	
	/**
	 * 
	 * @param Zend_Db_Table_Abstract $dbTable
	 * @return \Admin_Model_MapperAbstract
	 */
	public function setDbTable(Zend_Db_Table_Abstract $dbTable) {
		$this->_dbTable = $dbTable;

		return $this;
	}

	/**
	 * 
	 * @param array $data
	 * @return	mixed
	 */
	public function save(array $data) {
		if (null === ($id = $data['ID'])) {
			unset($data['ID']);
			return $this->getDbTable()->insert($data);
		} else {
			unset($data['ID']);
			return $this->getDbTable()->update($data, array('ID = ?' => $id));
		}
	}

	/**
	 * 
	 * @param type $id
	 * @return Object
	 */
	public function find($id) {
		$Result = $this->getDbTable()->find($id);
		if (0 == count($Result)) {
			return;
		}
		return $Result->current();
	}

	/**
	 * 
	 * @return array
	 */
	public function fetchAll($where = null, $order = null, $count = null, $offset = null) {
		return $this->getDbTable()->fetchAll($where, $order, $count, $offset);
	}
	
	/**
	 * 
	 * @param type $condition
	 * @param type $order
	 * @return Zend_Db_Table_Select
	 */
	protected function parseSelect($condition = array(), $order = null) {
		$Select = $this->getDbTable()->select()->from($this->getDbTable()->info(Zend_Db_Table_Abstract::NAME));//->where($condition['where'], $condition['value'], $condition['type'])->order($order);
		if (is_array($condition)) {
			foreach ($condition as $v) {
				if (is_array($v)) {
					$Select->where($v['where'], $v['value'], $v['type']);
				}
			}
		}
		
		$Select->order($order);
		
		return $Select;
	}

	/**
	 * 
	 * @param array $condition
	 * @param type $order
	 * @return \Zend_Paginator
	 */
	public function fetchPagination($condition = array(), $order = null) {
		$Select = $this->parseSelect($condition, $order);

		return new Zend_Paginator(new Zend_Paginator_Adapter_DbTableSelect($Select));
	}
}